package com.gable.exhibition.websocket;

import org.apache.log4j.Logger;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

/**
 * Created by Lesson on 2018/2/27.
 */
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    Logger logger = Logger.getLogger(this.getClass());

    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
                                   ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) {

        // 解决The extension [x-webkit-deflate-frame] is not supported问题
        if (request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
            request.getHeaders().set("Sec-WebSocket-Extensions",
                    "permessage-deflate");
        }

        logger.debug("Before Handshake");
        try{
            return super.beforeHandshake(request, response, wsHandler, attributes);
        }catch (Exception e){

        }

        return false;

    }

    @Override
    public void afterHandshake(ServerHttpRequest request,
                               ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception ex) {
        logger.debug("After Handshake");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
